package com.ztom.beans.factory.support.registry

import com.ztom.beans.exception.BeansException
import com.ztom.beans.factory.support.lifecycle.DisposableBean

/**
 * 单例 Bean 注册表默认实现
 *
 * @author ZhangTao
 */
open class DefaultSingletonBeanRegistry : SingletonBeanRegistry {

    private val singletonBeanMap = HashMap<String, Any>()

    private val disposableBeanMap = HashMap<String, DisposableBean>()

    override fun getSingleton(beanName: String): Any? {
        return singletonBeanMap[beanName]
    }

    override fun addSingleton(beanName: String, singletonBean: Any) {
        singletonBeanMap[beanName] = singletonBean
    }

    protected fun registerDisposableBean(beanName: String, bean: DisposableBean) {
        disposableBeanMap[beanName] = bean
    }

    fun destroySingletons() {
        val beanNames = disposableBeanMap.keys.toList()
        beanNames.forEach { beanName ->
            disposableBeanMap.remove(beanName)?.let {
                try {
                    it.destroy()
                } catch (e: Exception) {
                    throw BeansException("Destroy method on bean with name '$beanName' throws an exception", e)
                }
            }
        }
    }
}